package arch.chameleon.support.util;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator.Feature;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Json工具类
 * @author George
 *
 */
public class JsonUtils {

	private JsonUtils() {
	}

	/**
	 * 将对象转换成json字符串通过response输出
	 * @param jsonObj
	 * @param response
	 * @throws IOException
	 */
	public static void writeJson(Object jsonObj, HttpServletResponse response)
			throws IOException {
		if (response != null) {
			response.setCharacterEncoding("utf-8");
			if (jsonObj instanceof String) {
				response.getWriter().print((String) jsonObj);
			} else {
				response.getWriter().print(object2JsonString(jsonObj));
			}
			response.flushBuffer();
		} else {
			log.error("response is null");
		}
	}

	/**
	 * 对象转json字符串
	 * @param obj
	 * @return
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static String object2JsonString(Object obj)
			throws JsonGenerationException, JsonMappingException, IOException {
		ObjectMapper objectMapper = createObjectMapper();
		if (obj == null)
			return EMPTY_JSON_STRING;
		return objectMapper.writeValueAsString(obj);
	}
	
	/**
	 * json字符串转为Map对象
	 * @param <E>
	 * @param <V>
	 * @param strJsonString
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static<E, V> Map<E, V> jsonString2Map(String strJsonString) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper objectMapper = createObjectMapper();
		if(StringUtils.isBlank(strJsonString))strJsonString = EMPTY_JSON_STRING;
		return objectMapper.readValue(strJsonString, Map.class);		
	}

	
	/**
	 * 创建一个ObjectMapper实例
	 * @return
	 */
	public static ObjectMapper createObjectMapper() {
		JsonFactory objFac = new JsonFactory();
		objFac.configure(Feature.WRITE_NUMBERS_AS_STRINGS, true);
		return new ObjectMapper(objFac);
	}

	private final static String EMPTY_JSON_STRING = "{}";

	private transient static Logger log = LoggerFactory
			.getLogger(JsonUtils.class);
}
